﻿using System;
using WiMo.Games.Drawables;
using System.Drawing;

namespace WiMo.Games.Premium.GDIDisplay.Drawables
{
    public class SpriteText : SpriteTextBase
    {
        public SpriteText()
        {
            BackgroundColor = Color.Transparent;
        }

        public override void Dispose()
        {
            var font = Font.FontInformation as IDisposable;
            if (font != null)
                font.Dispose();

            Font.FontInformation = null;
        }

        private float GetScaledFontSize(int dpi, float fontSize)
        {
            switch (dpi)
            {
                case 96:
                    if (Scale.X != 1.0f && Scale.Y != 1.0f)
                        return fontSize * Scale.X;
                    break;
                case 128:
                    return fontSize / 1.5f;
                case 192:
                    if (Scale.X != 2.0f && Scale.Y != 2.0f)
                        return fontSize / 1.5f;
                    break;
            }

            return fontSize;
        }

        private Font CreateFont(int dpi)
        {
            var fontStyle = FontStyle.Regular;
            if (Font.Bold) fontStyle |= FontStyle.Bold;
            if (Font.Italics) fontStyle |= FontStyle.Italic;
            if (Font.Underline) fontStyle |= FontStyle.Underline;
            if (Font.StrikeThrough) fontStyle |= FontStyle.Strikeout;

            return new Font(Font.Name, GetScaledFontSize(dpi, Font.Size), fontStyle);
        }

        public void Render(IDisplay display, WiMo.Games.Rectangle destRect)
        {
            var displayManager = display as DisplayManager;

            if (Font.FontInformation == null)
                Font.FontInformation = CreateFont(displayManager.DPI);

            var image = DrawInformation as WiMoImage;

            if (image == null)
            {
                image = WiMoImage.CreateForText(displayManager.Graphics, this);
                DrawInformation = image;
            }

            var targetRect = BoundingRect.GetIntersection(destRect);
            var srcRect = new WiMo.Games.Rectangle(Math.Max(0, destRect.X - BoundingRect.X), Math.Max(0, destRect.Y - BoundingRect.Y), targetRect.Width, targetRect.Height);            

            displayManager.Graphics.DrawImage(image.BitmapImage, (targetRect + displayManager.DisplayOffset), srcRect, ColorKey);
        }

        public override void Render(IDisplay display)
        {
            var displayManager = display as DisplayManager;
            Render(displayManager, new WiMo.Games.Rectangle(0, 0, display.Size.Width, display.Size.Height));
        }

        public override bool CheckForCollision(ISprite sprite)
        {
            return false;
        }

    }
}
